package com.sgb.kjwl.view.ui.fragment.home;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.google.android.material.tabs.TabLayout;
import com.sgb.kjwl.AppFragment;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.FragmentWebsiteGoodsListBinding;
import com.sgb.kjwl.model.entity.manage.CategoriesGoodsEntity;
import com.sgb.kjwl.model.entity.request.MaterialFilterJson;
import com.sgb.kjwl.model.entity.user.ConcreteEntity;
import com.sgb.kjwl.model.entity.user.GoodsListEntity;
import com.sgb.kjwl.view.ui.activity.material.ConcreteDetailActivity2;
import com.sgb.kjwl.view.ui.activity.self.shop.ShopGoodsDetailActivity;
import com.sgb.kjwl.view.ui.adapter.search.WebGoodsMaterialAdapter;
import com.sgb.kjwl.viewmodel.home.WebSiteGoodsListModel;
import com.swgk.core.recyclerview.adapter.AdapterOnItemClick;
import com.swgk.core.util.SharedPreferenceUtil;
import com.swgk.core.util.StringUtil;
import com.swgk.core.xrecyclerview.XRecyclerView;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * @author qianghe
 * 说明：企业网站 -经营业务-商品经营
 * 时间：2021.05.25
 */
public class WebSiteGoodsListFragment extends AppFragment {

    private WebSiteGoodsListModel mViewModel;
    private FragmentWebsiteGoodsListBinding binding;
    private List<CategoriesGoodsEntity> categoriesGoodsEntityList;
    private int mPageNum = 1;
    private String mCid1;
    private String mCid2;
    private String mCid3;
    private int indexCid1;
    private int indexCid2;
    private final List<String> mBrandId = new ArrayList<>();
    private final List<String> mMaterValue = new ArrayList<>();
    private boolean isLoadMoreGoodsList;
    private WebGoodsMaterialAdapter mMaterialAdapter;
    private final List<String> mAreaId = new ArrayList<>();
    private final OnTabSelectedListener1 onTabSelectedListener1 = new OnTabSelectedListener1();
    private final OnTabSelectedListener2 onTabSelectedListener2 = new OnTabSelectedListener2();
    private final OnTabSelectedListener3 onTabSelectedListener3 = new OnTabSelectedListener3();
    private String companyNo = "";
    private String companyName = "";
    private String mLon = "0";
    private String mLat = "0";

    public static WebSiteGoodsListFragment newInstance(String websiteNo) {
        WebSiteGoodsListFragment webSiteGoodsListFragment = new WebSiteGoodsListFragment();
        Bundle bundle = new Bundle();
        bundle.putString("websiteNo", websiteNo);
        webSiteGoodsListFragment.setArguments(bundle);
        return webSiteGoodsListFragment;
    }

    @Nullable
    @Override
    public View onCreateView(@NotNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        binding = DataBindingUtil.inflate(inflater, R.layout.fragment_website_goods_list, container, false);
        return binding.getRoot();
    }

    @Override
    public void onViewCreated(@NonNull @NotNull View view, @Nullable @org.jetbrains.annotations.Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initView();
    }

    private void initView() {
        String websiteNo = "";
        if (getArguments() != null) {
            websiteNo = getArguments().getString("websiteNo");
        }
        binding.setLifecycleOwner(this);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
        binding.xrvFragmentGoodsMainGoodsList.setLayoutManager(linearLayoutManager);
        mMaterialAdapter = new WebGoodsMaterialAdapter(getContext(), null);
        mViewModel = new ViewModelProvider(this, new ViewModelProvider.AndroidViewModelFactory(requireActivity().getApplication())).get(WebSiteGoodsListModel.class);
        mViewModel.getWebsiteInfo(websiteNo, 1);
        mViewModel.websiteInfoEntityMutableLiveData.observe(getViewLifecycleOwner(), websiteInfoEntity -> {
            mViewModel.getReverseLookupTreeNode(websiteInfoEntity.getCompanyNo());
            companyNo = websiteInfoEntity.getCompanyNo();
            companyName = websiteInfoEntity.getName();
        });
        mViewModel.categoriesGoodsEntity.observe(getViewLifecycleOwner(), categoriesGoodsEntities -> {
            if (categoriesGoodsEntities != null && categoriesGoodsEntities.size() > 0) {

                CategoriesGoodsEntity children = new CategoriesGoodsEntity();
                children.setName("全部");
                categoriesGoodsEntities.add(0, children);

                for (CategoriesGoodsEntity categoriesGoodsEntity : categoriesGoodsEntities) {
                    List<CategoriesGoodsEntity.Children1> children1 = categoriesGoodsEntity.getChildren();
                    if (children1 == null) {
                        children1 = new ArrayList<>();
                    }
                    CategoriesGoodsEntity.Children1 children11 = new CategoriesGoodsEntity.Children1();
                    children11.setName("全部");
                    children1.add(0, children11);
                }

                for (CategoriesGoodsEntity categoriesGoodsEntity : categoriesGoodsEntities) {
                    List<CategoriesGoodsEntity.Children1> children1 = categoriesGoodsEntity.getChildren();
                    if (children1 == null) {
                        children1 = new ArrayList<>();
                    }
                    for (CategoriesGoodsEntity.Children1 children11 : children1) {
                        List<CategoriesGoodsEntity.Children1.Children2> children22 = children11.getChildren();
                        if (children22 == null) {
                            children22 = new ArrayList<>();
                        }
                        CategoriesGoodsEntity.Children1.Children2 children2 = new CategoriesGoodsEntity.Children1.Children2();
                        children2.setName("全部");
                        children22.add(0, children2);
                    }
                }
                categoriesGoodsEntityList = categoriesGoodsEntities;
                for (CategoriesGoodsEntity entity : categoriesGoodsEntities) {
                    binding.tlFragmentGoodsMainGoodsSelectTitle1.addTab(binding.tlFragmentGoodsMainGoodsSelectTitle1.newTab().setText(entity.getName()));
                }
            } else {
                binding.tlFragmentGoodsMainGoodsSelectTitle1.setVisibility(View.GONE);
                binding.tlFragmentGoodsMainGoodsSelectTitle2.setVisibility(View.GONE);
                binding.ivFragmentGoodsMainGoodsTag2.setVisibility(View.GONE);
                binding.tlFragmentGoodsMainGoodsSelectTitle3.setVisibility(View.GONE);
                binding.ivFragmentGoodsMainGoodsTag3.setVisibility(View.GONE);
                binding.xrvFragmentGoodsMainGoodsList.setVisibility(View.GONE);
                binding.blankView.setVisibility(View.VISIBLE);
            }
        });
        mViewModel.goodsListEntity.observe(getViewLifecycleOwner(), listListResponse -> showGoodsList(listListResponse.getList()));
        mViewModel.concreteListEntity.observe(getViewLifecycleOwner(), listListResponse -> {
            getConcreteList(listListResponse.getList());
        });
        mViewModel.msgLiveData.observe(getViewLifecycleOwner(), msg -> {
            binding.xrvFragmentGoodsMainGoodsList.refreshComplete();
            Toast.makeText(getActivity(), msg, Toast.LENGTH_LONG).show();
        });
        binding.tlFragmentGoodsMainGoodsSelectTitle2.setVisibility(View.GONE);
        binding.ivFragmentGoodsMainGoodsTag2.setVisibility(View.GONE);
        binding.tlFragmentGoodsMainGoodsSelectTitle3.setVisibility(View.GONE);
        binding.ivFragmentGoodsMainGoodsTag3.setVisibility(View.GONE);

        addOnTabSelectedListener();

        binding.xrvFragmentGoodsMainGoodsList.setAdapter(mMaterialAdapter);
        mMaterialAdapter.setOnItemClick(new AdapterOnItemClick<GoodsListEntity>() {
            @Override
            public void onItemClick(GoodsListEntity goodsListEntity, int position) {
                if (categoriesGoodsEntityList.get(binding.tlFragmentGoodsMainGoodsSelectTitle1.getSelectedTabPosition()).getId() == 7) {
                    MaterialFilterJson filterJson = new MaterialFilterJson();
                    filterJson.setStrengthId(goodsListEntity.getSort());
                    ConcreteDetailActivity2.start(getActivity(), goodsListEntity.getId(), filterJson);
                } else {
                    ShopGoodsDetailActivity.start(getContext(), goodsListEntity.getId(), "", goodsListEntity.getSkuid());
                }
            }
        });

        binding.xrvFragmentGoodsMainGoodsList.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                loadAllList(false);
            }

            @Override
            public void onLoadMore() {
                loadAllList(true);
            }
        });
    }

    private void addOnTabSelectedListener() {
        binding.tlFragmentGoodsMainGoodsSelectTitle1.addOnTabSelectedListener(onTabSelectedListener1);
        binding.tlFragmentGoodsMainGoodsSelectTitle2.addOnTabSelectedListener(onTabSelectedListener2);
        binding.tlFragmentGoodsMainGoodsSelectTitle3.addOnTabSelectedListener(onTabSelectedListener3);
    }

    class OnTabSelectedListener1 implements TabLayout.OnTabSelectedListener {

        @Override
        public void onTabSelected(TabLayout.Tab tab) {
            if (tab.getPosition() == 0) {
                mCid1 = "";
            } else {
                mCid1 = String.valueOf(categoriesGoodsEntityList.get(tab.getPosition()).getId());
            }
            mCid2 = "";
            mCid3 = "";
            indexCid1 = tab.getPosition();
            if (tab.getPosition() == 0) {
                binding.tlFragmentGoodsMainGoodsSelectTitle2.setVisibility(View.GONE);
                binding.ivFragmentGoodsMainGoodsTag2.setVisibility(View.GONE);
            } else {
                binding.tlFragmentGoodsMainGoodsSelectTitle2.setVisibility(View.VISIBLE);
                binding.ivFragmentGoodsMainGoodsTag2.setVisibility(View.VISIBLE);
            }
            binding.tlFragmentGoodsMainGoodsSelectTitle3.setVisibility(View.GONE);
            binding.ivFragmentGoodsMainGoodsTag3.setVisibility(View.GONE);
            refreshTabTitle(indexCid1, 0);
        }

        @Override
        public void onTabUnselected(TabLayout.Tab tab) {

        }

        @Override
        public void onTabReselected(TabLayout.Tab tab) {

        }
    }

    class OnTabSelectedListener2 implements TabLayout.OnTabSelectedListener {

        @Override
        public void onTabSelected(TabLayout.Tab tab) {
            indexCid2 = tab.getPosition();
            if (tab.getPosition() == 0) {
                mCid2 = "";
            } else {
                mCid2 = String.valueOf(categoriesGoodsEntityList.get(indexCid1).getChildren().get(indexCid2).getId());
            }
            mCid3 = "";
            if (tab.getPosition() == 0) {
                binding.tlFragmentGoodsMainGoodsSelectTitle3.setVisibility(View.GONE);
                binding.ivFragmentGoodsMainGoodsTag3.setVisibility(View.GONE);
            } else {
                binding.tlFragmentGoodsMainGoodsSelectTitle3.setVisibility(View.VISIBLE);
                binding.ivFragmentGoodsMainGoodsTag3.setVisibility(View.VISIBLE);
            }
            refreshTabTitle(indexCid1, indexCid2);
        }

        @Override
        public void onTabUnselected(TabLayout.Tab tab) {

        }

        @Override
        public void onTabReselected(TabLayout.Tab tab) {

        }
    }

    class OnTabSelectedListener3 implements TabLayout.OnTabSelectedListener {

        @Override
        public void onTabSelected(TabLayout.Tab tab) {
            if (tab.getPosition() == 0) {
                mCid3 = "";
            } else {
                mCid3 = String.valueOf(categoriesGoodsEntityList.get(indexCid1).getChildren().get(indexCid2).getChildren().get(tab.getPosition()).getId());
            }

            loadAllList(false);
        }

        @Override
        public void onTabUnselected(TabLayout.Tab tab) {

        }

        @Override
        public void onTabReselected(TabLayout.Tab tab) {

        }
    }

    /***
     * 设置二三级数据
     * @param indexCid1
     * indexCid2
     */
    private void refreshTabTitle(int indexCid1, int indexCid2) {
        if (indexCid1 == 0) {
            binding.tlFragmentGoodsMainGoodsSelectTitle2.removeAllTabs();
            binding.tlFragmentGoodsMainGoodsSelectTitle3.removeAllTabs();
        } else {
            binding.tlFragmentGoodsMainGoodsSelectTitle2.removeAllTabs();
            CategoriesGoodsEntity categoriesGoodsEntity = categoriesGoodsEntityList.get(indexCid1);
            for (CategoriesGoodsEntity.Children1 children2 : categoriesGoodsEntity.getChildren()) {
                binding.tlFragmentGoodsMainGoodsSelectTitle2.addTab(binding.tlFragmentGoodsMainGoodsSelectTitle2.newTab().setText(children2.getName()), false);
            }
            if (indexCid2 == 0) {
                binding.tlFragmentGoodsMainGoodsSelectTitle3.removeAllTabs();
            } else {
                binding.tlFragmentGoodsMainGoodsSelectTitle3.removeAllTabs();
                for (CategoriesGoodsEntity.Children1.Children2 children2 : categoriesGoodsEntityList.get(indexCid1).getChildren().get(indexCid2).getChildren()) {
                    binding.tlFragmentGoodsMainGoodsSelectTitle3.addTab(binding.tlFragmentGoodsMainGoodsSelectTitle3.newTab().setText(children2.getName()));
                }
            }
            binding.tlFragmentGoodsMainGoodsSelectTitle2.setScrollPosition(indexCid2, 0, true, true);
        }

        loadAllList(false);

    }

    private void loadAllList(boolean isLoadMore) {
        isLoadMoreGoodsList = isLoadMore;
        mPageNum = isLoadMore ? mPageNum + 1 : 1;
        Map<String, Object> map = new HashMap<>(16);
        map.put("pageNum", mPageNum);
        map.put("pageSize", 20);
        String mDistance = "";
        map.put("distance", mDistance);
        String mPriceSort = "0";
        map.put("priceSort", mPriceSort);
        map.put("timeSort", "0");
        map.put("cid1", mCid1);
        map.put("categoryId", mCid2);
        map.put("cid3", mCid3);
        map.put("itemId", "");
        map.put("brandId", mBrandId);

        map.put("regionCode", mAreaId);
        map.put("lon", "0".equals(mLon) ? SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LONGITUDE, "") : mLon);
        map.put("lat", "0".equals(mLat) ? SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LATITUDE, "") : mLat);
        String mCityId = "";
        map.put("areaId", mCityId);
        String mProvince = "";
        if ("7".equals(mCid1)) {
            map.put("supplierName", companyName);
            map.put("materValue", mMaterValue);
            mViewModel.getConcreteList(map, mProvince);
        } else {
            map.put("materValue", StringUtil.formatListToString(mMaterValue));
            List<String> companyList = new ArrayList<>(1);
            companyList.add(companyNo);
            map.put("companyNos", companyList);
            mViewModel.getGoodsList(map, mProvince);
        }
    }

    private void showGoodsList(List<GoodsListEntity> data) {
        binding.xrvFragmentGoodsMainGoodsList.refreshComplete();
        if (isLoadMoreGoodsList) {
            if (data != null && data.size() > 0) {
                binding.xrvFragmentGoodsMainGoodsList.loadMoreComplete();
                mMaterialAdapter.addDatas(data);
            } else {
                binding.xrvFragmentGoodsMainGoodsList.setNoMore(true);
            }
            binding.xrvFragmentGoodsMainGoodsList.setVisibility(View.VISIBLE);
        } else {
            binding.xrvFragmentGoodsMainGoodsList.refreshComplete();
            if (data.size() > 0) {
                binding.xrvFragmentGoodsMainGoodsList.setVisibility(View.VISIBLE);
                binding.blankView.setVisibility(View.GONE);
                mMaterialAdapter.setDatas(data);
                binding.xrvFragmentGoodsMainGoodsList.setLoadingMoreEnabled(true);
            } else {
                mMaterialAdapter.setDatas(null);
                binding.xrvFragmentGoodsMainGoodsList.setVisibility(View.GONE);
                binding.blankView.setVisibility(View.VISIBLE);
            }
        }
    }

    private void getConcreteList(List<ConcreteEntity> dataA) {
        List<GoodsListEntity> data = new ArrayList<>();
        for (ConcreteEntity concreteEntity : dataA) {
            data.add(new GoodsListEntity(true, "", concreteEntity.getDistance(), concreteEntity.getSelfSupportTag(), concreteEntity.getProviderName(), concreteEntity.getTitle(), 0, "", concreteEntity.getImage(), concreteEntity.getUnit(), concreteEntity.getCompanyNo()
                    , concreteEntity.getPrice(), "", concreteEntity.getId(), "", "", "", "", "", concreteEntity.getSort(), false, concreteEntity.getRanking(), concreteEntity.getStorageName(), concreteEntity.getLon(), concreteEntity.getLat(), concreteEntity.getLowestBuy(), concreteEntity.getImAccount()));
        }
        binding.xrvFragmentGoodsMainGoodsList.refreshComplete();
        if (isLoadMoreGoodsList) {
            if (data.size() > 0) {
                binding.xrvFragmentGoodsMainGoodsList.loadMoreComplete();
                mMaterialAdapter.addDatas(data);
            } else {
                binding.xrvFragmentGoodsMainGoodsList.setNoMore(true);
            }
            binding.xrvFragmentGoodsMainGoodsList.setVisibility(View.VISIBLE);
        } else {
            binding.xrvFragmentGoodsMainGoodsList.refreshComplete();
            if (data.size() > 0) {
                binding.xrvFragmentGoodsMainGoodsList.setVisibility(View.VISIBLE);
                binding.blankView.setVisibility(View.GONE);
                mMaterialAdapter.setDatas(data);
                binding.xrvFragmentGoodsMainGoodsList.setLoadingMoreEnabled(true);
            } else {
                mMaterialAdapter.setDatas(null);
                binding.xrvFragmentGoodsMainGoodsList.setVisibility(View.GONE);
                binding.blankView.setVisibility(View.VISIBLE);
            }
        }
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
    }

}
